package com.yeyks.rocketmq.service.customer;

import cn.hutool.json.JSONUtil;
import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.MessageListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.yeyks.common.constants.AccountType;
import com.yeyks.common.dto.mq.MiniCardOrderSuccessMessage;
import com.yeyks.commonReference.service.consumer.MemberCardService;
import com.yeyks.commonReference.service.vip.AccountVipSalerRelationService;
import com.yeyks.commonReference.service.vip.MemberCardEnableOrderService;
import com.yeyks.commonReference.service.vip.MiniCardCommissionOverviewService;
import com.yeyks.consumer.dal.domain.MemberCard;
import com.yeyks.vip.dal.domain.AccountVipSalerRelation;
import com.yeyks.vip.dal.domain.MemberCardEnableOrder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 会员卡支付成功监听
 *
 * @author shuai
 * @date 2020/01/09 14:52
 */
@Slf4j
@Component
public class MiniCardPaySuccessListener implements MessageListener {
    @Autowired
    private MemberCardEnableOrderService orderService;
    @Autowired
    private MemberCardService memberCardService;
    @Autowired
    private MiniCardCommissionOverviewService overviewService;
    @Autowired
    private AccountVipSalerRelationService vipSalerRelationService;

    @Override
    public Action consume(Message message, ConsumeContext consumeContext) {
        try {
            byte[] body = message.getBody();
            //获取到接收的消息，由于接收到的是byte数组，所以需要转换成字符串
            String msg = new String(body);
            log.info("会员卡支付成功：监听到的消息：message = {}", msg);
            MiniCardOrderSuccessMessage successMessage = JSONUtil.toBean(msg, MiniCardOrderSuccessMessage.class);
            if (null != successMessage) {
                //处理业务逻辑
                disposeLogic(successMessage);
            }
        } catch (Exception e) {
            log.error("会员卡支付成功监听异常错误信息:" + e.getMessage(), e);
        }
        return Action.CommitMessage;
    }

    /**
     * 处理卖卡成功后的逻辑
     *
     * @param message
     */
    private void disposeLogic(MiniCardOrderSuccessMessage message) {
        MemberCardEnableOrder one = orderService.getOne(new QueryWrapper<MemberCardEnableOrder>().eq(MemberCardEnableOrder.ORDER_NO, message.getOrderNo()));
        if (null == one) {
            log.info("该订单不存在orderNo = {}", message.getOrderNo());
            return;
        }
        if (!MemberCardEnableOrder.Status.success.value().equals(one.getStatus())) {
            log.info("该订单非支付成功状态orderNo = {}", message.getOrderNo());
            return;
        }
        //发放佣金
        //首先查询该卡是运营商售卖的还是卡商售卖的
        MemberCard memberCard = memberCardService.selectByCardNo(one.getCardNo());
        if (null == memberCard) {
            log.info("该订单订单对应的卡不存在cardOrder = {}", one);
            return;
        }
        //0运营商,如果是运营商(分佣40/99*订单金额)
        if (0 == memberCard.getSalerType()) {
            overviewService.orderCommission(memberCard.getSalerId(), AccountType.MinOperateMerchant, one.getOrderNo(), getAmount(4, one.getPayValue()));
        }
        //2卡商，如果是卡商(运营商分佣10/99*订单金额，卡商分佣30/99*订单金额)
        if (2 == memberCard.getSalerType()) {
            //给卡商分钱
            overviewService.orderCommission(memberCard.getSalerId(), AccountType.MinVipCardMerchant, one.getOrderNo(), getAmount(3, one.getPayValue()));
            //给运营商分钱
            //首先查询该卡商对应的运营商
            AccountVipSalerRelation relation = vipSalerRelationService.selectByAccountId(memberCard.getSalerId(), 2, AccountType.MinOperateMerchant);
            if (null != relation) {
                overviewService.orderCommission(relation.getParentId(), AccountType.MinOperateMerchant, one.getOrderNo(), getAmount(1, one.getPayValue()));
            }
        }
    }

    /**
     * 处理卖卡成功后的逻辑
     */
    public void testSellCardOrder(String orderNo) {
        try {
            MiniCardOrderSuccessMessage message = new MiniCardOrderSuccessMessage();
            message.setOrderNo(orderNo);
            disposeLogic(message);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("处理卖卡成功后的逻辑异常orderNo = {}", orderNo);
        }
    }


    private Integer getAmount(Integer type, Integer amount) {
        double result = 0D;
        if (1 == type) {
            result = 10D / 99D * amount;
        }
        if (3 == type) {
            result = 30D / 99D * amount;
        }
        if (4 == type) {
            result = 40D / 99D * amount;
        }
        return (int) result;
    }
}
